package com.caipiao.lottery.config;

/**
 * @author GaoFeng
 * @time 2014年1月13日
 * 
 */

import java.lang.reflect.Field;

import com.caipiao.lottery.log.TraceLogger;

public class ConfigAutoLoader implements Runnable
{
	//Bean路径
	//static String path = "com.caipiao.lottery.config.";
	
	public static boolean LoadConfig()
	{
		String[] cfgList = Config.Start.GetPropValue("Config").split(",");
		for (int i=0; i<cfgList.length;++i)
		{
			try
			{
				String obj_name = Config.Start.GetPropValue("Config.Object", cfgList[i]);
				
				String filePath = StartConfig.workDir + Config.Start.GetPropValue("Config.FileName", cfgList[i]);
				
				//静态对象反射
				Field obj = Config.class.getField(obj_name);
				ConfigInterface obj_inter = (ConfigInterface) obj.get(Config.class);
				
				if (null == obj_inter)
				{
					throw new Exception("未实现的配置:" + obj_name);
				}

				//配置重载
				if (!obj_inter.Load(filePath))
				{
					throw new Exception("加载失败:" + obj_name);
				}
				
				TraceLogger.System.info("ConfigAutoLoad配置加载完成:" + obj_name);
			}	
			catch(Exception e)
			{
				TraceLogger.System.error("ConfigAutoLoad配置加载异常:" + e);
				
				//日志记录
				return false;
			}
		}
		
		return true;
	}
	
	public void run()
	{
		//循环处理
		while (true) 
		{
			try 
			{
				String[] cfgList = Config.Start.GetPropValue("Config").split(",");
				
				for (int i=0; i<cfgList.length;++i)
				{
					try
					{
						String reload = Config.Start.GetPropValue("Config.Reload", cfgList[i]);
						
						if (reload.equalsIgnoreCase("1"))
						{
							String obj_name = Config.Start.GetPropValue("Config.Object", cfgList[i]);
							
							//静态对象反射
							Field obj = Config.class.getField(obj_name);
							ConfigInterface obj_inter = (ConfigInterface) obj.get(Config.class);

    						//配置重载
    						if (null != obj_inter && obj_inter.CheckLoad())
    						{
    							TraceLogger.System.info("ConfigAutoLoad检测到修改:" + obj_name);
    							
    							if (!obj_inter.ReLoad())
    							{
    								throw new Exception("重载失败:" + obj_name);
    							}
    							
    							TraceLogger.System.info("ConfigAutoLoad重载完成:" + obj_name);
    						}
						}
					}	
					catch(Exception e)
					{
						TraceLogger.System.error("ConfigAutoLoad配置自动重载异常:" + e);
					}
				}
				
				String auto_time = Config.Start.GetPropValue("AutoLoadTime");
				int ms = Integer.valueOf(auto_time);
				Thread.sleep(ms*1000);
			} 
			catch(Exception e)
			{
				try
				{
					Thread.sleep(60*1000);
				} 
				catch (InterruptedException e1)
				{
				}
			}
		}		
	}
	
	static Thread thrd = null;
	
	public static void Start() 
	{
		if (null == thrd)
		{
			thrd = new Thread(new ConfigAutoLoader());
		}
		thrd.start();
	}
	
	@SuppressWarnings("deprecation")
	public static void Stop()
	{
		if (null != thrd)
		{
			thrd.stop();
		}
	}
	
}
